package com.shanhy.baseproject.common.utils;

import java.util.Map;

import org.apache.commons.collections.MapUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;

/**
 * 类功能说明：httpclient工具类,基于httpclient 4.x
 *
 * @author   单红宇(CSDN catoop)
 * @create   2016年9月12日
 */
@Component
public class HttpClientUtils {

    private static final Logger LOGGER = LoggerFactory.getLogger(HttpClientUtils.class);

    @Autowired
    private RestClientUtils restClient;
    
    /**
     * post请求
     * @param url
     * @param formParams
     * @return
     */
    public String doPost(String url, Map<String, String> formParams) {
        if (MapUtils.isEmpty(formParams)) {
            return doPost(url);
        }

        try {
            MultiValueMap<String, String> requestEntity = new LinkedMultiValueMap<>();
            // jdk 1.8 lambda 表达式
//            formParams.keySet().stream().forEach(key -> requestEntity.add(key, MapUtils.getString(formParams, key, "")));
            for (String key : formParams.keySet()) {
            	requestEntity.add(key, MapUtils.getString(formParams, key, ""));
			}
            return restClient.getClient().postForObject(url, requestEntity, String.class);
        } catch (Exception e) {
            LOGGER.error("POST请求出错：{}", url, e);
        }

        return null;
    }

    /**
     * post请求
     * @param url
     * @return
     */
    public String doPost(String url) {
        try {
            return restClient.getClient().postForObject(url, HttpEntity.EMPTY, String.class);
        } catch (Exception e) {
            LOGGER.error("POST请求出错：{}", url, e);
        }

        return null;
    }

    /**
     * get请求
     * @param url
     * @return
     */
    public String doGet(String url) {
        try {
            return restClient.getClient().getForObject(url, String.class);
        } catch (Exception e) {
            LOGGER.error("GET请求出错：{}", url, e);
        }

        return null;
    }

}